﻿<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>分类管理</title>
	<link href="https://unpkg.com/layui@2.8.11/dist/css/layui.css" rel="stylesheet">
	<style>
		.layui-container {
			display: flex;
			gap: 20px;
			padding: 20px;
		}

		.left-tree {
			width: 300px;
			border-right: 1px solid #e6e6e6;
		}

			/* 树形样式优化 */
			.left-tree .layui-tree {
				height: calc(100vh - 140px); /* 根据页面布局调整高度 */
				overflow-y: auto;
			}

		.layui-tree-node {
			padding: 8px 0; /* 调整节点间距 */
		}

		.layui-tree-txt {
			font-size: 14px;
			color: #333;
		}


		.layui-input-inline {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.layui-input-inline .layui-form-label {
    width: 120px;
    color: #333;
    font-weight: 500;
    text-align: right;
    padding-right: 10px;
}

.layui-input-inline .layui-input,
.layui-input-inline .layui-select {
    height: 40px;
    flex: 1;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    padding: 0 15px;
    font-size: 14px;
    background: #fff;
    transition: border-color 0.3s ease;
}

.layui-input-inline .layui-input:focus,
.layui-input-inline .layui-select:focus {
    border-color: #1E9FFF;
    box-shadow: 0 0 0 2px rgba(30, 159, 255, 0.15);
}

.layui-input-inline .layui-btn {
    height: 40px;
    min-width: 80px;
    border-radius: 6px;
    font-size: 14px;
}


		#generateIdBtn {
			height: 40px;
			padding: 0 20px;
			border: 1px solid #1E9FFF;
			border-radius: 6px;
			background: linear-gradient(180deg, #1E9FFF 0%, #1A8CD8 100%);
			color: #fff;
			font-size: 14px;
			transition: all 0.3s ease;
			display: inline-flex;
			align-items: center;
			justify-content: center;
		}

			#generateIdBtn:hover {
				background: linear-gradient(180deg, #1A8CD8 0%, #1779C2 100%);
				border-color: #1779C2;
				transform: translateY(-1px); /* 悬停上移微动画 */
			}

			#generateIdBtn:active {
				transform: translateY(1px); /* 点击下移微动画 */
				background: #1779C2;
			}
		
	</style>
</head>
<body>
	<div class="layui-container">
		<div class="left-tree">

			<div id="materialsCopyDtos"></div>
		</div>

		<div class="right-form">
			<!-- 表单字段保持不变 -->
			<form class="layui-form layui-form-pane" id="permissionForm">

				<div class="layui-input-inline">

					<div class="layui-input-inline">
						<label class="layui-input-inline">* 分类编号</label>
						<div class="layui-input-inline">
							<input class="layui-input-inline" type="text" name="id" lay-verify="required" class="layui-input" id="categoryIdInput">
							<button class="layui-input-inline" type="button" class="layui-btn layui-btn-normal" id="generateIdBtn">自动生成</button>
						</div>
					</div>
					<br />
					<label class="layui-input-inline">* 上级分类</label>
					<div class="layui-input-inline">
						<select name="parent_category_id" lay-verify="required">
							<option value="0">请选择</option>
							<option value="1">成品</option>
							<option value="2">装配件</option>
							<option value="3">零部件</option>
							<option value="4">纸杯机</option>
							<option value="5">配套机</option>
							<option value="6">测试11</option>
							<option value="7">zj成品</option>
							<option value="8">框架</option>
							<option value="9">总成</option>
							<option value="10">原材料</option>
							<option value="11">五金件</option>
							<option value="12">包装物</option>
							<option value="13">半成品</option>
							<option value="14">螺钉</option>
						</select>
					</div>
				</div>
				<br />
				<div class="layui-input-inline">
					<label class="layui-input-inline">* 分类名称</label>
					<div class="layui-input-inline">
						<input type="text" name="title" lay-verify="required" class="layui-input">
					</div>
				</div>
				<br />
				<div class="layui-input-inline">
					<label class="layui-input-inline">计量单位</label>
					<div class="layui-input-inline">
						<select name="unit_of_measurement_id" id="selectDemo" lay-search>
							<option value="">请选择</option>
						</select>
					</div>
				</div>
				<br />
				<div class="layui-input-inline">
					<label class="layui-input-inline">* 流水号长度</label>
					<div class="layui-input-inline">
						<input type="number" name="serial_number_length" value="4" lay-verify="required" class="layui-input">
					</div>
				</div>
				<br />
				<div class="layui-input-inline">
					<label class="layui-input-inline">供应方式</label>
					<div class="layui-input-inline">
						<select name="supply_method_id" id="supplyMethodSelect" lay-search>
							<option value="">请选择</option>
						</select>
					</div>
				</div>
				<br />
				<div class="layui-input-inline">
					<label class="layui-input-inline">分类状态</label>
					<div class="layui-input-inline">
						<select name="supplyMethod">
							<option value="1">正常</option>
							<option value="2">停用</option>
						</select>
					</div>
				</div>
				<br />
				<div class="layui-form-item">
					<div class="layui-input-block">
						<button class="layui-btn layui-btn-blue" lay-submit lay-filter="WuLiao">确定</button>
						<button class="layui-btn layui-btn-normal" type="reset">重置</button>
					</div>
				</div>
			</form>

		</div>
	</div>

	<script src="https://unpkg.com/layui@2.8.11/dist/layui.js"></script>
	<script>
		layui.use(['tree', 'form', 'layer', 'jquery'], function () {
			var tree = layui.tree;
			var form = layui.form;
			var layer = layui.layer;
			var $ = layui.jquery;

			// 初始化树结构
			tree.render({
				elem: '#materialsCopyDtos',
				id: 'id',
				name: 'title',
				operable: true,
				templet: function (d) {
					return `
						<div class="layui-tree-txt">
							<i class="layui-tree-icon layui-icon layui-icon-layer"></i>
							${d.category_code || '未知编码'} - ${d.title || '未知名称'}
						</div>
					`;
				},
				icon: {
					"0": "layui-icon layui-icon-folder",
					"1": "layui-icon layui-icon-folder-open"
				}
			});

			// 加载树数据（修正数据格式）
			function loadTreeData() {
				$.ajax({
					//url: 'http://localhost:5234/api/Materials/GetMaterialsCopy',
					url: "@ViewBag.BaseUrl/T7/Materials/GetMaterialsCopy",
					method: 'GET',
					success: function (res) {
						if (res.data && Array.isArray(res.data)) {
							// 转换数据格式，确保包含id字段
							var formattedData = res.data.map(item => ({
								id: item.id,
								title: item.title,
								category_code: item.category_code,
								children: item.children || []
							}));
							tree.reload('id', { data: formattedData });
						} else {
							layer.msg('树数据加载失败', { icon: 2 });
						}
					},
					error: function (xhr) {
						layer.msg('树数据请求失败：' + xhr.status, { icon: 2 });
					}
				});
			}
			loadTreeData();


			// 点击树节点弹窗
			tree.on('node', function (obj) {
				var node = obj.data;
				console.log('点击的节点数据：', node); // 调试日志

				layer.open({
					type: 1,
					title: '分类详情',
					area: ['600px', '400px'],
					content: createPopupContent(node),
					success: function (layero, index) {
						loadCategoryDetails(node.id, layero);
					}
				});
			});

			// 创建弹窗内容模板
			function createPopupContent(node) {
				return `
							<div class="layui-padding">
								<h3>基本信息</h3>
								<table class="layui-table">
									<tr><td>分类编号：</td><td id="id"></td></tr>
									<tr><td>分类名称：</td><td id="title"></td></tr>
									<tr><td>上级分类：</td><td id="parent_category"></td></tr>
									<tr><td>创建时间：</td><td id="create_time"></td></tr>
								</table>
							</div>
						`;
			}

			// 加载详细数据（修正接口地址）
			function loadCategoryDetails(id, layero) {
				$.ajax({
					url: `http://localhost:5234/api/Materials/GetMaterialCategory/${id}`,
					method: 'GET',
					dataType: 'json',
					success: function (res) {
						console.log('接口响应：', res); // 调试日志
						if (res.code === 0) {
							var data = res.data;
							$(layero).find('#id').text(data.id);
							$(layero).find('#title').text(data.title);
							$(layero).find('#parent_category').text(data.parent_category_name || '无');
							$(layero).find('#create_time').text(formatDate(data.create_time));
						} else {
							layer.msg('数据加载失败：' + res.msg, { icon: 2 });
						}
					},
					error: function (xhr) {
						layer.msg('网络请求失败：' + xhr.status, { icon: 2 });
					}
				});
			}

			// 日期格式化
			function formatDate(timestamp) {
				var date = new Date(timestamp);
				return date.toLocaleString();
			}







			// 初始化计量单位下拉框数据
			initSelectData();
			function initSelectData() {
				$.ajax({
					type: 'GET',
					//url: 'http://localhost:5234/api/Materials/GetUnitOfMeasurement',  // 替换为实际接口地址
					url: "@ViewBag.BaseUrl/T7/Materials/GetUnitOfMeasurement",
					dataType: 'json',
					success: function (res) {
						if (res.code === 0) {
							var options = '';
							// 遍历后端返回数据
							$.each(res.data, function (index, item) {
								options += '<option value="' + item.unit_of_measurement_id + '">' + item.unit_of_measurement_name + '</option>';
							});
							// 添加到下拉框
							$('#selectDemo').append(options);
							// 渲染下拉框
							form.render('select');
						} else {
							layer.msg('获取数据失败：' + res.msg);
						}
					},
					error: function (xhr, status, error) {
						layer.msg('网络请求失败，请检查网络！');
						console.error(error);
					}
				});
			}
			// 监听下拉框选择事件
			form.on('select(selectDemo)', function (data) {
				console.log('选中的值：', data.value);
				console.log('选中的文本：', data.elem[data.elem.selectedIndex].text);
			});


			// 初始化下拉框数据
			function loadSupplyMethod() {
				$.ajax({
					type: 'GET',
					//url: 'http://localhost:5234/api/Materials/GetSupplyMethod', // 替换为实际后端接口地址
					url: "@ViewBag.BaseUrl/T7/Materials/GetSupplyMethod",
					dataType: 'json',
					success: function (res) {
						if (res.code === 0) {
							var options = '';
							$.each(res.data, function (index, item) {
								options += `<option value="${item.supply_method_id}">${item.supply_method_name}</option>`;
							});
							$('#supplyMethodSelect').append(options);
							form.render('select'); // 重新渲染下拉框
						} else {
							layer.msg('获取数据失败：' + res.msg);
						}
					},
					error: function () {
						layer.msg('网络请求失败，请检查网络！');
					}
				});
			}
			loadSupplyMethod(); // 初始化加载
			// 监听下拉框选择事件（可选）
			form.on('select(supplyMethodSelect)', function (data) {
				console.log('选中值：', data.value);
				console.log('选中文本：', data.elem[data.elem.selectedIndex].text);
			});






			// 新增：定义计数器，初始值17
			var currentCategoryId = 5;
			// 自动生成分类编号
			$('#generateIdBtn').on('click', function () {
				$('#categoryIdInput').val(currentCategoryId);
				currentCategoryId++; // 每次点击自增1
			});




			// 表单提交处理
			form.on('submit(WuLiao)', function (data) {
				var loadIndex = layer.load(2, { shade: 0.3 });
				var field = data.field;

				// 按后端模型严格匹配字段类型
				const convertedData = {
					id: field.id ? Number(field.id) : 0, // 确保默认值类型匹配
					parent_category_id: Number(field.parent_category_id) || 0,
					title: field.title || "string", // 提供默认字符串（按后端示例）
					unit_of_measurement_id: Number(field.unit_of_measurement_id) || 0,
					supply_method_id: Number(field.supply_method_id) || 0,
					supplyMethod: Number(field.supplyMethod) || 1,
					serial_number_length: Number(field.serial_number_length) || 0
				};


				$.ajax({
					//url: 'http://localhost:5090/api/Materials/AddMaterialCategory',
					url: "@ViewBag.BaseUrl/T8/Materials/AddMaterialCategory",
					method: 'post',
					contentType: 'application/json; charset=utf-8',
					data: JSON.stringify(convertedData),
					dataType: 'json',
					success: function (res) {
						layer.close(loadIndex);
						if (res.code === 212) {
							layer.msg('添加成功', { icon: 1 });
							$('#permissionForm')[0].reset();
							loadTreeData();
						} else {
							layer.msg('添加失败：' + (res.msg || '未知错误'), { icon: 2 });
						}
					},
					error: function (xhr) {
						layer.close(loadIndex);
						layer.msg('网络请求失败：' + xhr.status, { icon: 2 });
						console.error('请求详情：', xhr);
					}
				});

				return false; // 阻止表单默认提交
			});




		});
	</script>
</body>
</html>